<?php
header("Content-type: text/html; charset=utf-8");
session_start(); 
$cmd =  trim($_GET['cmd']);
$msg = $name = '';
$age = $high = $indexStart = 0;
extract($_GET);
class HTML {
    private static $pdo = null;

    public static function initSql(){
        self::$pdo = new PDO('mysql:host=localhost;dbname=sampleChat','root','root',array(PDO::MYSQL_ATTR_INIT_COMMAND => "set names utf8"));
    }
   
    public static function sendMsg(string $name = '',string $msg = ''){
        $statement = self::$pdo->prepare('INSERT INTO `msg` SET `name`=:name,`msg`=:msg,`itime`=:itime');
        $statement->bindValue(':name',htmlspecialchars($name),PDO::PARAM_STR);
        $statement->bindValue(':msg',htmlspecialchars($msg),PDO::PARAM_STR);
        $statement->bindValue(':itime',time(),PDO::PARAM_INT);
        $result = $statement->execute();
        if($result){
            return json_encode(array('code' => 1,'msg' => '数据插入成功！'));
        }else{
            return json_encode(array('code' => 0,'msg' => '数据插入失败！'));
        }
    }
    
    public static function obtainMsg(int $indexStart = 0){
        $statement = self::$pdo->prepare('SELECT `id`,`name`,`msg`,FROM_UNIXTIME(`itime`,"%H:%i:%s") AS `itime` FROM `msg` ORDER BY `itime` ASC LIMIT :indexStart,2147483647');
        $statement->bindValue(':indexStart',$indexStart,PDO::PARAM_INT);
        $statement->execute();
        $result = $statement->fetchAll(PDO::FETCH_ASSOC);
        if($result){
            return json_encode(array('code' => 1,'msg' => $result));
        }else{
            return json_encode(array('code' => 0,'msg' => '数据查询失败'));
        }
    }
    public static function getLastId(){
        $statement = self::$pdo->prepare('SELECT `id` FROM `msg` ORDER BY `id` DESC LIMIT 1');
        $statement->execute();
        $result = $statement->fetch(PDO::FETCH_ASSOC);
        if($result){
            return json_encode(array('code' => 1,'msg' => $result));
        }else{
            return json_encode(array('code' => 0,'msg' => '数据查询失败'));
        }
    }
}
HTML::initSql();
switch($cmd){
    case "sendMsg":
        echo HTML::sendMsg((string) $name,(string) $msg);
        exit();
        break;
    case "obtainMsg":
        echo HTML::obtainMsg((int) $indexStart);
        exit();
        break;
    case "getLastId":
        echo HTML::getLastId();
        exit();
        break;
    default:
        echo json_encode(array('status'=>8888,'msg'=>'无效的点击'));
        exit();
        break;
}
